var addOrEditTC_main = {
		//用例新增初始化信息获取
		insertCaseInitialCondition : function(){
			$.ajax({
    		    type : "get",
    		    async: false,//必须同步
    		    url : path+'/testCaseController/insertCaseInitialCondition',//找到controller里相应的方法
    		    success : function(dataMap) {
    		    	var assignerList = dataMap.assigner;
    		    	var areaList = dataMap.area;
    		    	var iterationList = dataMap.iteration;
    		    	var moduleList = dataMap.module;
    		    	//加载指派人下拉列表
    		    	$("#assignId").html("");
    		    	$(assignerList).each(function(index,assigner){
    		    		$("#assignId").append("<option value="+assigner.userId+">"+assigner.userName+"</option>");
    				});
    		    	//加载区域下拉列表
    		    	$("#areaId").html("");
    		    	$(areaList).each(function(index,area){
    		    		$("#areaId").append("<option value="+area.id+">"+area.name+"</option>");
    				});
    		    	//迭代下拉列表
    		    	$("#iterationId").html("");
    		    	$(iterationList).each(function(index,iteration){
    		    		$("#iterationId").append("<option value="+iteration.id+">"+iteration.name+"</option>");
    				});
    		    	//模块下拉列表
    		    	$("#moduleId").html("");
    		    	$(moduleList).each(function(index,module){
    		    		$("#moduleId").append("<option value="+module.moduleId+">"+module.moduleNm+"</option>");
    				});
    		    }
    		   });
		},
		 //用例编辑初始化信息获取
		getTestCase : function(){
			$.ajax({
    		    type : "get",
    		    async: false,//必须同步
    		    url : path+'/testCaseController/getTestCase?testcaseId='+testcaseId,//找到controller里相应的方法
    		    success : function(dataMap) {
    		    	var assignerList = dataMap.assigner;
    		    	var areaList = dataMap.area;
    		    	var iterationList = dataMap.iteration;
    		    	var moduleList = dataMap.module;
    		    	//加载指派人下拉列表
    		    	$("#assignId").html("");
    		    	$(assignerList).each(function(index,assigner){
    		    		$("#assignId").append("<option value="+assigner.userId+">"+assigner.userName+"</option>");
    				});
    		    	//加载区域下拉列表
    		    	$("#areaId").html("");
    		    	$(areaList).each(function(index,area){
    		    		$("#areaId").append("<option value="+area.id+">"+area.name+"</option>");
    				});
    		    	//迭代下拉列表
    		    	$("#iterationId").html("");
    		    	$(iterationList).each(function(index,iteration){
    		    		$("#iterationId").append("<option value="+iteration.id+">"+iteration.name+"</option>");
    				});
    		    	//模块下拉列表
    		    	$("#moduleId").html("");
    		    	$(moduleList).each(function(index,module){
    		    		$("#moduleId").append("<option value="+module.moduleId+">"+module.moduleNm+"</option>");
    				});
    		    	//回显测试用例名称 
    		    	$('#name').val(dataMap.testcase.name);
    		    	//回显指派人名称 
    		    	$('#assignId').val(dataMap.testcase.assignId);
    		    	//回显区域值
    		    	$('#areaId').val(dataMap.testcase.areaId);
    		    	//回显状态值
    		    	$('#state').val(dataMap.testcase.state);
    		    	//回显迭代值
    		    	$('#iterationId').val(dataMap.testcase.iterationId);
    		    	//回显优先级值
    		    	$('#priority').val(dataMap.testcase.priority);
    		    	//回显模块值
    		    	$('#moduleId').val(dataMap.testcase.moduleId);
    		    	//回显测试方式值
    		    	$('#executionType').val(dataMap.testcase.executionType);
    		    	//回显摘要值
    		    	$('#summary').val(dataMap.testcase.summary);
    		    	//给模块信息变量赋值 
    		    	data={
	    				"total": dataMap.tcstep.length,
	    				"rows": dataMap.tcstep
	    			};
    		    	//给附件信息变量赋值 
    		    	data_attachments = dataMap.attachment;
    		    	addOrEditTC_main.initGrid();
    		    }
    		   });
			
		},
		getTestCaseRelation: function(){
			$.ajax({
    		    type : "get",
    		    async: true,
    		    url : path+'/testCaseController/getTestCaseRelation?testcaseId='+testcaseId,//找到controller里相应的方法
    		    beforeSend:function(xmlHttp){
    			},
    		    complete: function (jqXHR) {
    		    },
    		    success : function(data) {
    		    	//给所有链接信息变量赋值 
    		    	data_links = data;
    		    	//所有链接表格
    				 $('#linkTb').bootstrapTable({
    			            cache:false,
    			            pagination:false,
    			            striped: true,
    			            pageNumber:1,
    			            singleSelect:true,
    			            clickToSelect:true,
    			            data:data_links,
    			            queryParams:function(params){
    			                var parm = {};
    			                parm['pageSize'] = params.limit || 15 ;
    			                parm['pageIndex'] = (params.offset / params.limit) + 1 || 1;
    			                return parm;
    			            },
    			            method: "get",
    			            dataType: "json",
    			            columns: [{
    			                title: '',//标题  可不加，
    			                checkbox:true,
    			                width: "6%"
    			            }, {
    			                field: 'destinationType',
    			                title: '工作项类型',
    			                formatter:function(value,row,index){
    			        			var typeName = '';
    			        			if(value == 1){
    			        				typeName = "测试用例";
    			        			}else{
    			        				typeName = value;
    			        			}
    			        			return typeName;
    			        		}
    			            }, {
    			                field: 'name',
    			                title: '标题'
    			            }, {
    			                field: 'relationType',
    			                title: '链接类型'
    			            }]
    			        });
    		    }
    		   });
		},
		initGrid : function(){
			 //可编辑步骤表格
	        $('#stepTable').grid({
	            singleSelect: true,
//	             disableSelect: true,
	            data:data,
	            pageSize: 5,
	            condensed: true,
	            columns: [
	            	{field: '', title: '', checkbox: true, width: 50},
	                {field: 'action', title: '操作', editor: 'text', width: 250},
	                {field: 'expectedResult', title: '预期结果', editor: 'text', width: 250}
	            ],
	            onDblClickRow: function(rowIndex, rowData){
	            	 $('#stepTable').grid('beginEdit', rowIndex);
	            }
	        });
//			//所有链接表格
//			 $('#linkTb').bootstrapTable({
//		            cache:false,
//		            pagination:false,
//		            striped: true,
//		            pageNumber:1,
//		            singleSelect:true,
//		            clickToSelect:true,
//		            data:data_links,
//		            queryParams:function(params){
//		                var parm = {};
//		                parm['pageSize'] = params.limit || 15 ;
//		                parm['pageIndex'] = (params.offset / params.limit) + 1 || 1;
//		                return parm;
//		            },
//		            method: "get",
//		            dataType: "json",
//		            columns: [{
//		                title: '',//标题  可不加，
//		                checkbox:true,
//		                width: "6%"
//		            }, {
//		                field: 'destinationType',
//		                title: '工作项类型',
//		                formatter:function(value,row,index){
//		        			var typeName = '';
//		        			if(value == 1){
//		        				typeName = "测试用例";
//		        			}else{
//		        				typeName = value;
//		        			}
//		        			return typeName;
//		        		}
//		            }, {
//		                field: 'name',
//		                title: '标题'
//		            }, {
//		                field: 'relationType',
//		                title: '链接类型'
//		            }]
//		        });
			//附件表格 
			 $('#attachmentTable').bootstrapTable({
		            cache:false,
		            pagination:false,
		            striped: true,
		            pageNumber:1,
		            singleSelect:true,
		            clickToSelect:true,
		            data:data_attachments,
		            queryParams:function(params){
		                var parm = {};
		                parm['pageSize'] = params.limit || 15 ;
		                parm['pageIndex'] = (params.offset / params.limit) + 1 || 1;
		                return parm;
		            },
		            method: "get",
		            dataType: "json",
		            columns: [{
		                title: '',//标题  可不加，
		                checkbox:true,
		                width: "6%"
		            }, {
		                field: 'fileName',
		                title: '名称'
		            }, {
		                field: 'fileSize',
		                title: '大小'
		            }, {
		                field: 'dateAdded',
		                title: '附加日期',
		                formatter:function(value,row,index){
		                	if(value == ""){
		                		return "";
		                	}else{
		                		return new Date(value).Format("yyyy-MM-dd hh:mm:ss");
		                	}
		                }
		            }]
		        });
		},
		create_initGrid : function(){

			 //可编辑步骤表格
	        $('#stepTable').grid({
	            singleSelect: true,
//	             disableSelect: true,
	            data:{},
	            pageSize: 5,
	            condensed: true,
	            columns: [
	            	{field: '', title: '', checkbox: true, width: 50},
	                {field: 'action', title: '操作', editor: 'text', width: 250},
	                {field: 'expectedResult', title: '预期结果', editor: 'text', width: 250}
	            ],
	            onDblClickRow: function(rowIndex, rowData){
	            	 $('#stepTable').grid('beginEdit', rowIndex);
	            }
	        });
			//所有链接表格
			 $('#linkTb').bootstrapTable({
		            cache:false,
		            pagination:false,
		            striped: true,
		            pageNumber:1,
		            singleSelect:true,
		            clickToSelect:true,
		            data:[],
		            queryParams:function(params){
		                var parm = {};
		                parm['pageSize'] = params.limit || 15 ;
		                parm['pageIndex'] = (params.offset / params.limit) + 1 || 1;
		                return parm;
		            },
		            method: "get",
		            dataType: "json",
		            columns: [{
		                title: '',//标题  可不加，
		                checkbox:true,
		                width: "6%"
		            }, {
		                field: 'destinationType',
		                title: '工作项类型',
		                formatter:function(value,row,index){
		        			var typeName = '';
		        			if(value == 1){
		        				typeName = "测试用例";
		        			}else{
		        				typeName = value;
		        			}
		        			return typeName;
		        		}
		            }, {
		                field: 'name',
		                title: '标题'
		            }, {
		                field: 'relationType',
		                title: '链接类型'
		            }]
		        });
			//附件表格 
			 $('#attachmentTable').bootstrapTable({
		            cache:false,
		            pagination:false,
		            striped: true,
		            pageNumber:1,
		            singleSelect:true,
		            clickToSelect:true,
		            data:[],
		            queryParams:function(params){
		                var parm = {};
		                parm['pageSize'] = params.limit || 15 ;
		                parm['pageIndex'] = (params.offset / params.limit) + 1 || 1;
		                return parm;
		            },
		            method: "get",
		            dataType: "json",
		            columns: [{
		                title: '',//标题  可不加，
		                checkbox:true,
		                width: "6%"
		            }, {
		                field: 'fileName',
		                title: '名称'
		            }, {
		                field: 'fileSize',
		                title: '大小'
		            }, {
		                field: 'dateAdded',
		                title: '附加日期',
		                formatter:function(value,row,index){
		                	if(value == ""){
		                		return "";
		                	}else{
		                		return new Date(value).Format("yyyy-MM-dd hh:mm:ss");
		                	}
		                }
		            }]
		        });
		
			
			
			
		},
		//打开新建连接弹框页
		createLink : function(){
			$('#create_relationType').val("");
			$('#create_name').val("");
			$('#createLinkForm').data('bootstrapValidator').resetForm(true);
		      
			layer.open({
				type : 1,
				title : '链接新工作项页',
				fix : true,
				scrollbar : false,
				area : [ '550px', '320px' ],
				shift : 2,
				content : $('#createLinkHtml'),
				btn:['确定','取消'],
				success: function(layero, index){
					if(!$('.layui-layer-title').has('span').length){
						 $(".layui-layer-title").prepend("<span class='glyphicon glyphicon-th-large' ></span>&nbsp;");
					 }
					layerFlag = "createLink";
					setTimeout(function() {
						  addOrEditTC_hidden_relateLink.relationTypeList();
					}, 0);
			  	},
				end : function() {
					layerFlag = "";
				},
				yes: function(index, layero){
					addOrEditTC_main.saveCreateLink();
				},
				btn2: function(index, layero){
				    //按钮【按钮二】的回调
				  },
			});
		},
		saveCreateLink : function(){
			var bootstrapValidator = $("#createLinkForm").data('bootstrapValidator').validate();
	    	if(bootstrapValidator.isValid()){
	    		var params = {
						"insertFlag":insertFlag,
						"name":$('#create_name').val()
				};
				$.ajax({
	    	        type : "post",
	    	        url :path+'/testCaseController/insertTestCase',//找到controller里相应的方法
	    	        data : params, //把数组的值赋给data，把上面的param改为data,这里就能直接去掉
	    	        dataType : "json",//根据数据类型选择text、jason等
	    	        success : function(data) { 
	    	        	if(data.result == true){
	    	        		var temporaryId = new Date().getTime();
	    	        		var destinationType = $('#create_itemType').val();
	    	        		var relationTypeId = $('#create_relationType').val(); 
	    					var relationType ="";
	    						relationType = $('#create_relationType option[value="'+relationTypeId+'"]').text();
	    					var destinationId = data.msg;
	    					var name = $('#create_name').val();
	    					$("#linkTb").bootstrapTable('append', {"relationId":"temporaryId_"+temporaryId,"relationTypeId":relationTypeId,"destinationId":destinationId,"destinationType":destinationType,"name":name,"relationType":relationType,"ifInner":"true"});
			        		layer.closeAll();
			        		toast.success('操作成功！','成功提示');
			        	}else{
			        		toast.error('操作失败！','失败提示');
			        	}
	    	        }
	    	       });
	    	}
			
		},
		//打开克隆弹框页面
		copyCase : function(){
			$("#projectId").val("");
			$('#cloneForm').data('bootstrapValidator').resetForm(true);
			var lable_tcName = $('#name').val();
			$('#clone_lable').text("创建测试用例【"+lable_tcName+"】的副本。");
			layer.open({
				type : 1,
				title : '复制工作项',
				fix : true,
				scrollbar : false,
//		 		maxmin: true, //开启最大化最小化按钮
				area : [ '550px', '400px' ],
				shift : 2,
				content : $('#cloneHtml'),
				btn:['确定','取消'],
				success: function(layero, index){
					if(!$('.layui-layer-title').has('span').length){
						 $(".layui-layer-title").prepend("<span class='glyphicon glyphicon-th-large' ></span>&nbsp;");
					 }
					layerFlag = "clone";
					setTimeout(function() {
						addOrEditTC_hidden_clone.listProject();
						addOrEditTC_hidden_clone.projectOnchange();
					}, 0);
			  	},
				end : function() {
					layerFlag = "";
				},
				yes: function(index, layero){
					addOrEditTC_hidden_clone.copyCaseSubmit();
				  },
				btn2: function(index, layero){
				    //按钮【按钮二】的回调
				  },
			});
			
		},
		//打开创建bug弹框页面
		createBug : function(){
			layer.open({
				type : 2,
				title : '创建bug',
				fix : true,
				scrollbar : false,
				area : [ '750px', '420px' ],
				shift : 2,
				content : path+'/testCaseController/createBug',
				btn: ['确定', '取消'],
					yes : function(index, layer) {
			            var iframeWin = layer.find('iframe')[0];
			            iframeWin.contentWindow.submit(); 
			        },
			        btn2:function(index, layer) {
			        },
		        success: function(layero, index){
					if(!$('.layui-layer-title').has('span').length){
						 $(".layui-layer-title").prepend("<span class='glyphicon glyphicon-th-large' ></span>&nbsp;");
					 }
					layerFlag = "createBug";
			  	},
				end : function(){
					layerFlag = "";
				}
			});
		},
		//新建用例页面保存提交
		createSubmit : function(){
			 var testcase ={};
			 	//给模块信息变量赋值 testcaseId
			 	testcase["testcaseId"] = testcaseId;
				 testcase["name"] = $('#name').val();
				 testcase["assignId"] = $('#assignId').val();
				 testcase["areaId"] = $('#areaId').val();
				 testcase["state"] = $('#state').val();
				 testcase["iterationId"] = $('#iterationId').val();
				 testcase["priority"] = $('#priority').val();
				 testcase["moduleId"] = $('#moduleId').val();
				 testcase["executionType"] = $('#executionType').val();
				 testcase["summary"] = $('#summary').val();
			 	var stepData=$('#stepTable').grid('getData');
				var stepTotal = stepData.rows.length;
				for(var i = 0; i < stepTotal; i++){					
					$('#stepTable').grid('beginEdit', i);			
				}
				var stepParamArray = [];
				for(var i = 0; i < stepTotal; i++){					
					$('#stepTable').grid('endEdit', i);		
					var rowData = $('#stepTable').grid('getRow', i);
					var action = rowData.action;
					var expectedResult = rowData.expectedResult;
					var stepParams = {
							"action":action,
							"expectedResult":expectedResult,
							"stepNumber":i+1
					};
					stepParamArray.push(stepParams);
				}
				$("#tcsteps").val(JSON.stringify(stepParamArray));
				
				var linkData = $('#linkTb').bootstrapTable('getData');
				var linkTotal = linkData.length;
				var linkParamArray = [];
				for(var i = 0; i < linkTotal; i++){		
					var relationTypeId = linkData[i].relationTypeId;
					var destinationId = linkData[i].destinationId;
					var destinationType = linkData[i].destinationType;
					var name = linkData[i].name;
					var relationType = linkData[i].relationType;
					var ifInner = linkData[i].ifInner;
					
					var linkParams = {
							"relationTypeId":relationTypeId,
							"destinationId":destinationId,
							"destinationType":destinationType,
							"name":name,
							"relationType":relationType,
							"ifInner":ifInner
					};
					linkParamArray.push(linkParams);
				}
				$("#relations").val(JSON.stringify(linkParamArray));
				
				$("#testCaseForm").ajaxSubmit({
					type : "POST",
					url : path+'/testCaseController/insertTestCase',
					processData:false,
					dataType : 'json',
			        success : function(data) {
			        	if(data.result == true){
			        		parent.loadFlag = 1;
			        		parent.layer.closeAll();
			        		parent.toast.success('操作成功！','成功提示');
			        	}else{
			        		toast.error('操作失败！','失败提示');
			        	}
			        }
				});
		},
		//编辑用例页面保存提交
		updateSubmit : function(){
			 var testcase ={};
			 	//给模块信息变量赋值 testcaseId
			 	testcase["testcaseId"] = testcaseId;
				 testcase["name"] = $('#name').val();
				 testcase["assignId"] = $('#assignId').val();
				 testcase["areaId"] = $('#areaId').val();
				 testcase["state"] = $('#state').val();
				 testcase["iterationId"] = $('#iterationId').val();
				 testcase["priority"] = $('#priority').val();
				 testcase["moduleId"] = $('#moduleId').val();
				 testcase["executionType"] = $('#executionType').val();
				 testcase["summary"] = $('#summary').val();
			 	var stepData=$('#stepTable').grid('getData');
				var stepTotal = stepData.rows.length;
				for(var i = 0; i < stepTotal; i++){					
					$('#stepTable').grid('beginEdit', i);			
				}
				var stepParamArray = [];
				for(var i = 0; i < stepTotal; i++){					
					$('#stepTable').grid('endEdit', i);		
					var rowData = $('#stepTable').grid('getRow', i);
					var action = rowData.action;
					var expectedResult = rowData.expectedResult;
					var stepParams = {
							"action":action,
							"expectedResult":expectedResult,
							"stepNumber":i+1
					};
					stepParamArray.push(stepParams);
				}
				$("#tcsteps").val(JSON.stringify(stepParamArray));
				var linkData = $('#linkTb').bootstrapTable('getData');
				var linkTotal = linkData.length;
				var linkParamArray = [];
				for(var i = 0; i < linkTotal; i++){		
					var relationId = linkData[i].relationId;
					var relationTypeId = linkData[i].relationTypeId;
					var destinationId = linkData[i].destinationId;
					var destinationType = linkData[i].destinationType;
					var ifInner = linkData[i].ifInner;
					var name = linkData[i].name;
					var relationType = linkData[i].relationType;
					var linkParams;
					if(relationId.indexOf("temporaryId_") >= 0){
						linkParams = {
								"relationId":"",
								"relationTypeId":relationTypeId,
								"destinationId":destinationId,
								"destinationType":destinationType,
								"name":name,
								"relationType":relationType,
								"ifInner":ifInner
						};
					}else{
						linkParams = {
								"relationId":relationId,
								"relationTypeId":relationTypeId,
								"destinationId":destinationId,
								"destinationType":destinationType,
								"name":name,
								"relationType":relationType,
								"ifInner":ifInner
						};
					}
					linkParamArray.push(linkParams);
				}
				$("#relations").val(JSON.stringify(linkParamArray));
				var attachData = $('#attachmentTable').bootstrapTable('getData');
				var attachTotal = attachData.length;
				var attachParamArray = [];
				for(var i = 0; i < attachTotal; i++){				 
					var attachmentId = attachData[i].attachmentId;
					var fileName = attachData[i].fileName;
					var fileSize = attachData[i].fileSize;
					var dateAdded = attachData[i].dateAdded;
					var attachParams = {
							"attachmentId":attachmentId,
							"fileName":fileName,
							"fileSize":fileSize,
							"dateAdded":dateAdded
					};
					if(attachmentId.indexOf("temporaryId_") < 0){
						attachParamArray.push(attachParams);
					}
				}
				$("#attachments").val(JSON.stringify(attachParamArray));
				
				$("#testCaseForm").ajaxSubmit({
					type : "POST",
					url : path+'/testCaseController/updateTestCase',
					processData:false,
					dataType : 'json',
			        success : function(data) {
			        	if(data.result == true){
			        		parent.loadFlag = 1;
			        		parent.layer.closeAll();
			        		parent.toast.success('操作成功！','成功提示');
			        	}else{
			        		toast.error('操作失败！','失败提示');
			        	}
			        }
				});
		}
}

var addOrEditTC_step = {
		initMethod : function(){
			 $('#btnappendRow').click(function () {
		        	var data=$('#stepTable').grid('getData');
		        	var total = data.rows.length;
		            $('#stepTable').grid('appendRow', {action: "", expectedResult: ""});
		            $('#stepTable').grid('beginEdit', total);
		        });
			 //插入步骤
		        $('#btninsertRow').click(function () {
		        	var index = $(".coodo-grid-data-row-selected").attr("coodo-grid-rowindex");
//		        	var index = $('#stepTable').grid('getRowIndex', $('#stepTable').grid('getSelected'));
		        	if(index == -1 || index == "" || index == undefined){
		        		toast.info ('请先选择一条信息！','信息提示');
		        	}else{
		        		index = parseInt(index);
		        		 $('#stepTable').grid('insertRow', {index: index, row: {action: "", expectedResult: ""}});
				         $('#stepTable').grid('beginEdit', index);
		        	}
		        });
		        //删除步骤按钮事件触发
		        $('#btndeleteRow').click(function () {
		        	var index = $(".coodo-grid-data-row-selected").attr("coodo-grid-rowindex");
//		        	var index = $('#stepTable').grid('getRowIndex', $('#stepTable').grid('getSelected'));
		        	if(index == -1 || index == "" || index == undefined){
		        		toast.info ('请先选择一条信息！','信息提示');
		        	}else{
		        		index = parseInt(index);
		        		$('#stepTable').grid('deleteRow', index);
		        	}
		        });

			//上移步骤触发事件
		        $('.up').click(function(){
					var rows = document.getElementById('stepTable').getElementsByTagName('tr');
					var upflag = 0;
					for(var i = 0; i < rows.length; i++){
						if($(rows[i]).hasClass("coodo-grid-data-row-selected")){
							upflag = 1;
							break;
						}
					}
					if(upflag == 0){
						toast.info ('请先选择一条信息！','信息提示');
					}else if(upflag == 1){
						var selectedRow;
						for(var i = 0; i < rows.length; i++){
							if($(rows[i]).hasClass("coodo-grid-data-row-selected")){
								selectedRow = rows[i];
								var selectedTds= $(selectedRow).find('.coodo-grid-rowNumber');
								if(i == 0){
									toast.info ('已经是最顶部了！','信息提示');
								}else{
									//将选中的上一行数据的index和rownumber加1
									$(rows[i-1]).attr("coodo-grid-rowindex",i);
									var upTds= $(rows[i-1]).find('.coodo-grid-rowNumber');
									$(upTds[0]).text(i+1);
									//将选中行数据的index和rownumber减1
									$(selectedRow).attr("coodo-grid-rowindex",i-1);
									$(selectedTds[0]).text(i);
								}
								break;
							}
						}
						//当前tr插入到前一个tr的前面
						$(selectedRow).prev().before(selectedRow);
					}
					
				});
		      //下移步骤触发事件
		    	$('.down').click(function(){
		    		var rows = document.getElementById('stepTable').getElementsByTagName('tr');
		    		var downflag = 0;
					for(var i = 0; i < rows.length; i++){
						if($(rows[i]).hasClass("coodo-grid-data-row-selected")){
							downflag = 1;
							break;
						}
					}
					if(downflag == 0){
						toast.info ('请先选择一条信息！','信息提示');
					}else if(downflag == 1){
						var selectedRow;
						for(var i = 0; i < rows.length; i++){
							if($(rows[i]).hasClass("coodo-grid-data-row-selected")){
								selectedRow = rows[i];
								var selectedTds= $(selectedRow).find('.coodo-grid-rowNumber');
								if(i == rows.length-1){
									toast.info ('已经是最底部了！','信息提示');
								}else{
									//将选中的下一行数据的index和rownumber减1
									$(rows[i+1]).attr("coodo-grid-rowindex",i);
									var upTds= $(rows[i+1]).find('.coodo-grid-rowNumber');
									$(upTds[0]).text(i+1);
									//将选中行数据的index和rownumber加1
									$(selectedRow).attr("coodo-grid-rowindex",i+1);
									$(selectedTds[0]).text(i+2);
								}
								break;
							}
						}
						//当前div插入到后一个div的后面
						$(selectedRow).next().after(selectedRow);
					}
				});
		}
};
//所有连接tap页面触发事件
var addOrEditTC_relation = {
		//打开链接已有工作项弹框页面
		relateLink : function(){
			$('#relate_itemType').val("1");
			$('#relate_relationType').val("");
			$('#relate_workItem').val("");
			
			$('#relateLinkForm').data('bootstrapValidator').resetForm(true);
			layer.open({
				type : 1,
				title : '链接已有工作项页',
				fix : true,
				scrollbar : false,
//		 		maxmin: true, //开启最大化最小化按钮
				area : [ '550px', '320px' ],
				shift : 2,
				content : $('#relateLinkHtml'),
				btn:['确定','取消'],
				success: function(layero, index){
					if(!$('.layui-layer-title').has('span').length){
						 $(".layui-layer-title").prepend("<span class='glyphicon glyphicon-th-large' ></span>&nbsp;");
					 }
					layerFlag = "relateLink";
					setTimeout(function() {
						addOrEditTC_hidden_relateLink.relationTypeList();
						addOrEditTC_hidden_relateLink.relate_itemType_onchange();
					}, 0);
					
			  	},
				yes: function(index, layero){
					addOrEditTC_relation.saveRelateLink();
				},
				btn2: function(index, layero){
				    //按钮【按钮二】的回调
				  },
			  end : function() {
				  layerFlag = "";
				}
			});
		}, 
		saveRelateLink : function(){
			var temporaryId = new Date().getTime();
			var destinationType = $('#relate_itemType').val();
			var relationTypeId = $('#relate_relationType').val(); 
			var relationType = $('#relate_relationType option[value="'+relationTypeId+'"]').text();
			var destinationId = $('#relate_workItem').val();
			var name = $('#relate_workItem option[value="'+destinationId+'"]').text();
			var ifInner = "true";
			if(destinationType == "2"){
				ifInner = "false";
				destinationType = $('#relate_workItem option:selected').attr("issuetypename");
			}
			//判断是否以同样链接关系关联了该工作项
			var bootstrapValidator = $("#relateLinkForm").data('bootstrapValidator').validate();
	    	if(bootstrapValidator.isValid()){
	    		var relateLinkFlag = 0;
	    		var linkData = $('#linkTb').bootstrapTable('getData');
    			for(var i = 0; i < linkData.length; i++){
    				if(destinationId == linkData[i].destinationId && relationTypeId == linkData[i].relationTypeId){
    					relateLinkFlag = 1;
    					toast.info ('已有重复项不可添加！','信息提示'); 
    					break;
    				}
    			}
    			if(relateLinkFlag == 0){
    				$("#linkTb").bootstrapTable('append', {"relationId":"temporaryId_"+temporaryId,"relationTypeId":relationTypeId,"destinationId":destinationId,"destinationType":destinationType,"name":name,"relationType":relationType,"ifInner":ifInner});
    				layer.closeAll();
    			}
	    	}
		},
		//打开连接弹框
		openLink : function(){
			var getSelections = $('#linkTb').bootstrapTable('getSelections');
			if(getSelections.length == 1){
				var destinationId = getSelections[0].destinationId;
				parent.layer.open({
					type : 2,
					title : '编辑用例',
					fix : true,
					scrollbar : false,
					area : [ '800px', '500px' ],
					shift : 2,
					content : path+'/testCaseController/addOrEditTestCase?destinationId='+destinationId,
					btn: ['确定', '取消'],
						yes : function(index, layer) {
				            var iframeWin = layer.find('iframe')[0];
				            iframeWin.contentWindow.submit(); 
				        },
				        btn2:function(index, layer) {
				        },
			        success: function(layero, index){
						if(!$('.layui-layer-title').has('span').length){
							 $(".layui-layer-title").prepend("<span class='glyphicon glyphicon-th-large' ></span>&nbsp;");
						 }
				  	}
				});
			}else{
				toast.info ('请选择一行需要处理的信息！','信息提示'); 
			}
		},
		//删除连接数据
		deleteLinkRows : function(){
			 var ids = $.map($("#linkTb").bootstrapTable('getSelections'), function (row) {
				 return row.relationId;
	            });
			 if(ids.length < 1){
				 toast.info ('请选择您需要处理的信息！','信息提示');
			 }else{
				 layer.confirm('确定要删除选中的信息吗？', {icon: 3, title:'<span class="glyphicon glyphicon-th-large"></span>&nbsp;提示'}, function(){
					 $("#linkTb").bootstrapTable('remove', {
			                field: "relationId",
			                values: ids
			            });
					 layer.closeAll();
					 toast.success('操作成功！','成功提示');
				});
			 }
		}
};

var addOrEditTC_attachment = {
		uploadAttachment : function(){
			$('#attachmentHtml .create_input').html(
					'<input type="file" class="form-control" name="files" class="file" onchange="fileChange(this);">');
			layer.open({
				type : 1,
				title : '上传附件',
				fix : true,
				scrollbar : false,
//		 		maxmin: true, //开启最大化最小化按钮
				area : [ '500px', '220px' ],
				shift : 2,
				content : $('#attachmentHtml'),
				btn:['确定','取消'],
				success: function(layero, index){
					if(!$('.layui-layer-title').has('span').length){
						 $(".layui-layer-title").prepend("<span class='glyphicon glyphicon-th-large' ></span>&nbsp;");
					 }
			  	},
				end : function() {
				},
				yes: function(index, layero){
					
					var fileContent = $('#attachmentHtml .create_input>input[type="file"]').val();
					if(fileContent != ""){
						var temporaryId = new Date().getTime();
						$('#attachmentHtml .create_input>input[type="file"]').attr("temporaryId", "temporaryId_"+temporaryId);
						$('#attachmentHtml .create_input>input[type="file"]').addClass("hidden");
						$('#testCaseForm').append($('#attachmentHtml .create_input>input[type="file"]'));
						$('#attachmentHtml .create_input').html("");
						var ids = $.map($("#attachmentTable").bootstrapTable('getData'), function (row) {
							if(row.attachmentId.indexOf("temporaryId_") >= 0){
								return row.attachmentId;
							}
			            });
						$("#attachmentTable").bootstrapTable('remove', {
			                field: 'attachmentId',
			                values: ids
			            });
						var fileList = addOrEditTC_attachment.getFileNameAndSize('files');
						$(fileList).each(function(index,file){
							$("#attachmentTable").bootstrapTable('append', {"attachmentId":file.temporaryId,"fileName":file.name,"fileSize":file.size,"dateAdded":""});
						});
						 layer.closeAll();
					}else{
						toast.info ('请选择您需要上传的文件！','信息提示');
					}
				  },
				btn2: function(index, layero){
				    //按钮【按钮二】的回调
				  },
			});
		},
		//获取文件的名字和大小 
		getFileNameAndSize : function(fileId){
			var dom = document.getElementsByName(fileId);  
			var fileList = [];
			for(var i = 0; i < dom.length; i++){
				var temporaryId = $(dom[i]).attr("temporaryId");
//				var temporaryId = dom[i].attributes[3].nodeValue;
				var fileLength = dom[i].files.length;
				for(var j = 0; j < fileLength; j++){
					var name = dom[i].files.item(j).name;
					var size = dom[i].files.item(j).size;
					fileList.push({"name":name,"size":size,"temporaryId":temporaryId});
				}
			}
            return fileList;
		},
		//下载附件
		downloadFile : function(){
			var getAttachSelections = $("#attachmentTable").bootstrapTable('getSelections');
			if(getAttachSelections.length == 1){
				var attachmentId = getAttachSelections[0].attachmentId;
				if(attachmentId.indexOf("temporaryId_") >= 0){
					toast.info ('该附件尚未上传，暂不能下载！','信息提示');
				}else{
					window.location.href=path+'/testCaseController/downloadFile?attachmentId='+attachmentId;
				}
			}else{
				toast.info ('请选择一条需要处理的信息！','信息提示'); 
			}
		},
		//删除附件信息
		delAttachmentRows : function(){
			var ids = $.map($("#attachmentTable").bootstrapTable('getSelections'), function (row) {
				 return row.attachmentId;
	            });
			 if(ids.length < 1){
				 toast.info ('请选择您需要处理的信息！','信息提示');
			 }else{
				 layer.confirm('确定要删除选中的信息吗？', {icon: 3, title:'<span class="glyphicon glyphicon-th-large"></span>&nbsp;提示'}, function(){
					 $("#attachmentTable").bootstrapTable('remove', {
			                field: "attachmentId",
			                values: ids
			            });
					 for(var i = 0; i < ids.length; i++){
						 if(ids[i].indexOf("temporaryId_") >= 0){
							 var dom = document.getElementsByName('files');
							 for(var j = 0; j < dom.length; j++){
									var temporaryId = dom[j].attributes[3].nodeValue;
									if(ids[i] == temporaryId){
										dom[j].remove();
									}
							 }
						 }
					 }
					 layer.closeAll();
					 toast.success('操作成功！','成功提示');
				});
			 }
		}
};

addOrEditTC_hidden_clone = {
		listProject : function(){
			$.ajax({
			    type : "get",
			    url : path+'/basic/getProjectByUser',//找到controller里相应的方法
			    success : function(dataList) {
    		    	//加载项目下拉列表
    		    	$("#projectId").html("<option value=''>请选择</option>");
    		    	$(dataList).each(function(index,data){
    		    		$("#projectId").append("<option value="+data.projectId+">"+data.projectName+"</option>");
    				});
			    }
			   });
		},
		//改变项目下拉框触发事件
		projectOnchange : function(){
			var projectId = $('#projectId option:selected').val();
			if(projectId == ""){
    			$('#testplanId').html("");
    			$('#menu_id').val("");
    			$('#menu_parent_name').val("");
    			document.getElementById("treediv").innerHTML = "";
    		}else{
    			addOrEditTC_hidden_clone.listTestPlan(projectId);
    			$('#menu_id').val("");
    			$('#menu_parent_name').val("");
    			document.getElementById("treediv").innerHTML = "";
    		}
		},
		//查询项目下的测试计划
		listTestPlan : function(projectId){
			$.ajax({
			    type : "get",
			    url : path+'/testCaseController/listTestPlan?projectId='+projectId,//找到controller里相应的方法
			    success : function(dataList) {
    		    	//加载计划下拉列表
    		    	$("#testplanId").html("<option value=''>请选择</option>");
    		    	$(dataList).each(function(index,data){
    		    		$("#testplanId").append("<option value="+data.id+">"+data.name+"</option>");
    				});
			    }
			   });
		},
		//改变测试计划下拉框触发事件
		testPlanOnchange : function(){
			var testplanId = $('#testplanId option:selected').val();
			if(testplanId == ""){
				$('#menu_id').val("");
    			$('#menu_parent_name').val("");
    			document.getElementById("treediv").innerHTML = "";
    		}else{
    			$('#menu_id').val("");
    			$('#menu_parent_name').val("");
    			addOrEditTC_hidden_clone.listTestSuite(testplanId);
    		}
		},
		//根据测试计划查询测试套件
		listTestSuite : function(testplanId){
			$.ajax({
			    type : "get",
			    url : path+'/testCaseController/listTestSuiteByTestPlanId?testplanId='+testplanId,//找到controller里相应的方法
			    success : function(dataList) {
			    	mydtree = new dTree('mydtree','imgmenu/','no','no');
			    	mydtree.add(testplanId,
							  -1,
							  "请选择节点",
							  "javascript:setvalue()",
							  "请选择节点",
							  "_self",
							  false);
	  		    	//加载套件树形结构
	  		    	$(dataList).each(function(index,data){
	  		    		mydtree.add(data.id,
	  		    				data.parentId,
	  		    				data.name,
	  		    				"javascript:setvalue('"+data.id+"','"+data.name+"')",
	  		    				data.name,
	  		    				'_self',
	  		    				false);
	  				});
					document.getElementById("treediv").innerHTML = mydtree;//局部流输出
			    }
			   });
		},
		copyCaseSubmit : function(){
			var bootstrapValidator = $("#cloneForm").data('bootstrapValidator').validate();
			if(bootstrapValidator.isValid()){
				var cloneTestsuiteId = "";
				if($("#testplanId").val() != ""){
					if($("#menu_id").val() != ""){
						cloneTestsuiteId = $("#menu_id").val();
					}else{
						cloneTestsuiteId = $("#testplanId").val();
					}
				}
				var params = {
						"testcaseId": testcaseId,
						"cloneProjectId": $("#projectId").val(),
						"cloneTestsuiteId":cloneTestsuiteId
				};
				$.ajax({
	    	        type : "post",
	    	        url :path+'/testCaseController/cloneTestCase',//找到controller里相应的方法
	    	        data : params, //把数组的值赋给data，把上面的param改为data,这里就能直接去掉
	    	        dataType : "json",//根据数据类型选择text、jason等
	    	        success : function(data) { 
	    	        	if(data.result == true){
	    	        		if($('#projectId').val() == currentProjectId){
	            	        	var relationId = data.relationId;
	            	        	var name = data.name;
	            	        	$("#linkTb").bootstrapTable('append', {"relationId":relationId,"relationTypeId":"4","destinationId":"","destinationType":"测试用例","name":name,"relationType":"is cloned by","ifInner":"true"});
	    	        		}
	    	        		layer.closeAll();
	    	        		toast.success('操作成功！','成功提示');
	    	        	}else{
	    	        		toast.error('操作失败！','失败提示');
	    	        	}
	    	        }
	    	       });
			}
			}
};

var addOrEditTC_hidden_relateLink = {
		relationTypeList : function(){
			$.ajax({
			    type : "get",
			    url : path+'/testCaseController/listRelationType',//找到controller里相应的方法
			    success : function(dataList) {
    		    	//加载已有工作项下拉列表
    		    	$("#relate_relationType").html("<option value=''>请选择</option>");
    		    	$(dataList).each(function(index,data){
    		    		$("#relate_relationType").append("<option value="+data.relationTypeId+">"+data.relationType+"</option>");
    				});
    		    	//加载连接新工作项下拉列表
    		    	$("#create_relationType").html("<option value=''>请选择</option>");
    		    	$(dataList).each(function(index,data){
    		    		$("#create_relationType").append("<option value="+data.relationTypeId+">"+data.relationType+"</option>");
    				});
			    }
			   });
		},
		relate_itemType_onchange : function(){
			var relate_itemType = $('#relate_itemType option:selected').val();
			if(relate_itemType == "1"){
				$.ajax({
				    type : "get",
				    url : path+'/testCaseController/listLinkTestCase',//找到controller里相应的方法
				    success : function(dataList) {
	    		    	//加载已有工作项下拉列表
	    		    	$("#relate_workItem").html("<option value=''>请选择</option>");
	    		    	$(dataList).each(function(index,data){
	    		    		$("#relate_workItem").append("<option value="+data.testcaseId+">"+data.name+"</option>");
	    				});
				    }
				   });
			}else if(relate_itemType == "2"){
				$.ajax({
				    type : "get",
				    url : path+'/testCaseController/listJiraIssue',//找到controller里相应的方法
				    success : function(dataList) {
	    		    	//加载已有工作项下拉列表
	    		    	$("#relate_workItem").html("<option value=''>请选择</option>");
	    		    	$(dataList).each(function(index,data){
	    		    		$("#relate_workItem").append("<option value="+data.issueId+" issueTypeName="+data.issueTypeName+">"+"["+data.issueKey+"]"+data.summary+"</option>");
	    				});
				    }
				   });
			}
		}
};
